/*
 * @Author: Drc
 * @Date: 2020-06-22 09:43:34
 * @LastEditors: Drc
 * @LastEditTime: 2020-11-25 16:31:09
 */

const fs = require('fs')
const path = require('path')
const prettier = require('prettier')
//读取目录
const Dir = path.resolve(__dirname, '../')
//支持语言
const supportLanguage = ['zh', 'en']
//导出目录
function outputDir(language = supportLanguage[0]) {
  return path.resolve(__dirname, `../i18n/${language}.ts`)
}
//读取的文件类型
const fileTypes = ['png', 'jpg', 'jpeg', 'gif']
//格式化配置
let prettierConfig = {}

//读取Dir下所有文件
function readFiles() {
  return new Promise((resolve, reject) => {
    fs.readdir(Dir, function (err, files) {
      if (err) {
        reject(err)
      }
      if (!files) {
        reject()
        return
      }

      //过滤不支持的后缀文件
      let filterFiles = files.filter((filename) => {
        return fileTypes.includes(filename.slice(filename.lastIndexOf('.') + 1, filename.lastIndexOf('.') + 4))
      })
      Promise.all(filterFiles.map((filename) => readfile(filename)))
        .then((data) => resolve(data))
        .catch((readErr) => reject(readErr))
    })
  })
}

//读取单个文件
function readfile(filename) {
  return new Promise((resolve, reject) => {
    fs.readFile(path.join(Dir, filename), 'utf8', (err, data) => {
      let replaceName = filename
      //替换倍图符号
      if (replaceName.includes('@')) {
        replaceName = replaceName.replace(/@(\S*)x/g, '')
      }
      if (err) {
        reject(err)
      }
      //判断语言处理
      let key = replaceName.split('.')[0] + ''
      let language = supportLanguage[0]
      for (let item of supportLanguage) {
        let mark = `_${item}`
        if (key.endsWith(mark)) {
          language = item
          key = key.substring(0, key.length - mark.length)
        }
      }

      resolve({
        language,
        data: {
          [key]: `require('../${replaceName}')`,
        },
      })
    })
  })
}

async function getPrettierOption() {
  prettierConfig = (await prettier.resolveConfig('.')) ?? {}
}

//处理
function handleData(data) {
  let languageData = {}
  supportLanguage.map((item) => {
    languageData[item] = {keys: [], values: {}}
  })

  data.map((item, index) => {
    let key = Object.keys(item.data)[0]
    //key去重
    if (!languageData[item.language].keys.includes(key)) {
      let value = item.data[key]
      languageData[item.language].keys.push(key)
      languageData[item.language].values[key] = value
    }
  })

  Object.keys(languageData).map((language) => {
    //构造import
    let importOutput = ''

    //构造对象
    let obj = JSON.stringify(languageData[language].values).replace(/\"/g, '')

    if (language !== supportLanguage[0]) {
      //import默认语言
      importOutput = `import ${supportLanguage[0]} from './${supportLanguage[0]}'`
      //对象添加import的语言
      obj = obj.replace('{', `{...${supportLanguage[0]},`)
    }
    let objOutput = 'export default ' + obj + 'as const'

    //合并最终导出文件
    let outputFile = importOutput + '\n\n' + objOutput

    const prettierFile = prettier.format(outputFile, {...prettierConfig, parser: 'typescript'})
    fs.writeFileSync(outputDir(language), prettierFile, function (err) {
      if (err) {
        throw new Error(err)
      }
    })
  })
}

//执行
readFiles()
  .then((data) => {
    getPrettierOption().finally(() => {
      handleData(data)
    })
  })
  .catch((err) => {
    throw new Error(err)
  })
